package com.android.svmc.app.mobile.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import luyenlv.pro.screen.base.BaseActivity;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.svmc.app.mobile.adapter.CommentAdapter;
import com.android.svmc.app.mobile.controller.WifiManagement;
import com.android.svmc.app.mobile.data.DatabaseSource;
import com.android.svmc.app.mobile.data.JsonData;
import com.android.svmc.app.mobile.model.CommentModel;
import com.android.svmc.app.mobile.model.PictureModel;
import com.android.svmc.app.mobile.model.PostDetail;
import com.android.svmc.app.mobile.util.CommonDefine;
import com.android.svmc.app.mobile.view.CustomDialog;


public class DetailPostActivity extends BaseActivity implements
		OnClickListener, CommonDefine {
	// variabale
	private int ID_Post;
	private int id_activity ;
	private String content;
	private String title_post;
	private ArrayList<CommentModel> listcomment;
	private CommentAdapter commentAdapter;
	// view
	private Button submit_comment,label_btn_comment;
	private ProgressDialog dialog;
	private WebView webview;
	private ImageView button_comment_label;
	private ListView listview_comment;
	private RelativeLayout main,rl_comment;
	private View footer,header;
	private ProgressBar loading;
	public static EditText form_input_comment;
	private LinearLayout line_label_comment;
	private RelativeLayout rl_loadingcontent;
	// constant
	private boolean isShow = false;
	// async task
	private loadComment load_comment_asynctask;
	private loadContent load_content_asynctask;
	private submitComment submit_comment_asynctask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(getLayout(R.array.detailpost_layout));
		//setContentView(R.layout.post_detail_320);
		/*************************************
		 *  Get Data
		 ************************************/
		Bundle data = getIntent().getExtras();
		id_activity = data.getInt(ID_ACTIVITY);
		ID_Post = data.getInt(ID_POST);
		title_post = data.getString(TITLE);
		/***********************************/
		initUI();
		setclicklistener();
		fillData();
		Log.i("anhson", "onCreate() DetailPostActivity");
		SharedPreferences mPreferences =PreferenceManager.getDefaultSharedPreferences(DetailPostActivity.this);
		String name_comment = mPreferences.getString(NAME_SUBMIT_COMMENT, "Ẩn danh");
		Log.i("anhson", name_comment);
	}
	private void initUI(){
		main = (RelativeLayout)findViewById(R.id.post_detail_rl_main);
		//main.setVisibility(View.GONE);
		TextView title = (TextView) findViewById(R.id.post_detail_titlebar_txt_title);
		if (title_post.length() > 14 ){
			title.setText(title_post.substring(0, 14)+"...");
		}else {
			title.setText(title_post);
		}		

		findViewById(R.id.post_detail_btn_back).setOnClickListener(this);
		loading =(ProgressBar)findViewById(R.id.postdetail_progressBar_loading);
		loading.setVisibility(View.VISIBLE);
		listview_comment =(ListView)findViewById(R.id.postdetail_ls_comment);
		listview_comment.setDivider(null);
		listview_comment.setDividerHeight(0);
		listcomment=new ArrayList<CommentModel>();
		
		/********************************************
		 * Add Header and Footer
		 *******************************************/
		header = getLayoutInflater().inflate(R.layout.header_detailpost, listview_comment, false);
		webview =(WebView)header.findViewById(R.id.header_postdetail_webview_content);
		button_comment_label = (ImageView)header.findViewById(R.id.postdetail_img_show_comment);
		label_btn_comment =(Button)header.findViewById(R.id.postdetail_btn_comment_label);
		rl_comment =(RelativeLayout)header.findViewById(R.id.header_postdetail_rl_comment);
		line_label_comment = (LinearLayout)header.findViewById(R.id.postdetail_ll_line);
		listview_comment.addHeaderView(header);
		/********************************************/
		footer = getLayoutInflater().inflate(R.layout.footer_detailpost, listview_comment,false);
		form_input_comment = (EditText)footer.findViewById(R.id.postdetail_edt_form_comment);
		submit_comment = (Button) footer.findViewById(R.id.postdetail_btn_submit_comment);
		listview_comment.addFooterView(footer);
		footer.setVisibility(View.GONE);
		listview_comment.setAdapter(new CommentAdapter(this, listcomment));
		/*********************************/
		rl_loadingcontent = (RelativeLayout)findViewById(R.id.postdetail_rl_loadcontent);
	}
	private void setclicklistener(){
	    button_comment_label.setOnClickListener(this);
	    label_btn_comment.setOnClickListener(this);
	    rl_comment.setOnClickListener(this);
	    line_label_comment.setOnClickListener(this);
		submit_comment.setOnClickListener(this);
	}
	public void fillData (){
		//new loadContent().execute();
		load_content_asynctask = new loadContent();
		load_content_asynctask.execute();
	}

	@Override
	public void clearMemory() {
		unbindReferences(this, R.id.post_detail_rl_main);

	}
	public class loadContent extends AsyncTask<Void, Void, Void> {
		PostDetail post;
		PictureModel picture;
		@Override
		protected Void doInBackground(Void... arg0) {
			if(id_activity == POST_ACTIVITY){
				if(WifiManagement.haveNetworkConnection() == true ){
					JsonData json = new JsonData(DetailPostActivity.this);
					post = json.getPost(ID_Post);	
				}else {
					DatabaseSource db = new DatabaseSource(DetailPostActivity.this);
					post = db.getpPostByIdServer(ID_Post);
					Log.i(TAG, post.getContent());
				}
				
			}else if (id_activity == PICTURE_ACTIVITY) {
				JsonData json = new JsonData(DetailPostActivity.this);
				picture = json.getPicture(ID_Post);
			}				
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			//dialog.dismiss();
			listview_comment.setVisibility(View.VISIBLE);
			rl_loadingcontent.setVisibility(View.GONE);
			main.setVisibility(View.VISIBLE);
			webview.setVisibility(View.VISIBLE);
			if(id_activity==POST_ACTIVITY){
				content = post.getContent();
			}else if (id_activity == PICTURE_ACTIVITY) {
				content = picture.getContent();
			}
			webview.setWebViewClient(new WebViewClient(){

				@Override
				public void onPageFinished(WebView view, String url) {
					super.onPageFinished(view, url);
					loading.setVisibility(View.GONE);
				}

				@Override
				public void onPageStarted(WebView view, String url,
						Bitmap favicon) {
					super.onPageStarted(view, url, favicon);
					loading.setVisibility(View.VISIBLE);
				}

				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					
					return true;
				}			
			});
			
			webview.loadDataWithBaseURL(null, "<html><body>"+content+"</body></html>","text/html", "UTF-8", null);
			webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
			webview.getSettings().setBuiltInZoomControls(true);
			webview.getSettings().setSupportZoom(true);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			webview.setVisibility(View.GONE);
			rl_loadingcontent.setVisibility(View.VISIBLE);
			listview_comment.setVisibility(View.GONE);
			loading.setVisibility(View.GONE);
		}

	}

	/**
	 * Get context in groupActivity.Use for show dialog
	 * 
	 * @return : context
	 */
	private Context getDialogContext() {
		Context mcontext;
		if (getParent() != null)
			mcontext = getParent();
		else
			mcontext = this;
		return mcontext;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		form_input_comment = null;
		submit_comment = null;
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if( load_content_asynctask !=null && !load_content_asynctask.isCancelled()){
			load_content_asynctask.cancel(true);
		}
		if(load_comment_asynctask != null && !load_comment_asynctask.isCancelled()){
			load_comment_asynctask.cancel(true);
		}
		if(submit_comment_asynctask !=null && !submit_comment_asynctask.isCancelled()){
			submit_comment_asynctask.cancel(true);
		}
		Log.i("anhson", "onDestroy() DetailPostActivity");

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.post_detail_btn_back:
			this.finish();
			break;
		case R.id.postdetail_btn_comment_label:
		case R.id.postdetail_ll_line:
		case R.id.header_postdetail_rl_comment:
		case R.id.postdetail_img_show_comment:
			if(WifiManagement.haveNetworkConnection()){
				if( isShow == true){
					button_comment_label.setImageResource(R.drawable.button_comment);
					isShow = false;
					listcomment.clear();
					commentAdapter.notifyDataSetChanged();
					footer.setVisibility(View.GONE);
				}else {
					button_comment_label.setImageResource(R.drawable.button_comment_down);
					isShow= true;
					getComment();
					
				}
			}else {
				Toast.makeText(this,getString(R.string.not_support_comment_in_offline_mode), 0).show();
			}

			break;
		case R.id.postdetail_btn_submit_comment:
			if(form_input_comment.getText().toString().equalsIgnoreCase("")==true){
				Toast.makeText(this, "Không được bỏ trống khi nhấn nút gửi", Toast.LENGTH_SHORT).show();
			}else {
				//new submitComment().execute();
				submit_comment_asynctask = new submitComment();
				submit_comment_asynctask.execute();
			}
			
			break;
		default:
			break;
		}

	}
	public void getComment (){
		if (WifiManagement.haveNetworkConnection()){
			load_comment_asynctask = new loadComment();
			load_comment_asynctask.execute();
		}
		
	}
	public class loadComment extends AsyncTask<Void, Void, Void> {
		
		@Override
		protected Void doInBackground(Void... arg0) {
			JsonData json = new JsonData(DetailPostActivity.this);
			if(id_activity==POST_ACTIVITY){
				listcomment = json.getAllComment(ID_Post,URL_GET_DETAIL_POST);
			}else if (id_activity == PICTURE_ACTIVITY) {
				listcomment = json.getAllComment(ID_Post, URL_GET_DETAIL_PICTURE);
				
			}
			
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			dialog.dismiss();
			listview_comment.setVisibility(View.VISIBLE);
			footer.setVisibility(View.VISIBLE);
			commentAdapter = new CommentAdapter(DetailPostActivity.this, listcomment);
			if (listview_comment != null && commentAdapter != null) {
				listview_comment.setAdapter(commentAdapter);
				commentAdapter.notifyDataSetChanged();
				listview_comment.setSelection(listview_comment.getBottom());
				form_input_comment.requestFocus();
				
			}
			
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(getDialogContext());
			dialog.setMessage("Đang tải thảo luận...");
			dialog.setCancelable(false);
			dialog.show();
		}
	}
	public String sendPostRequestComment(String url,String name){
		StringBuilder stringBuilder = null;
		//String urlpost = url+""+ID_Post+"&name="+name+"&email="+"sentertainment@smail.com"+"&content="+form_input_comment.getText().toString();
		//Log.i("anhson", urlpost);
		String urlpost = url+""+ID_Post;
		DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(urlpost);
		
		BasicNameValuePair name_submit = new BasicNameValuePair("name",name);
		BasicNameValuePair email = new BasicNameValuePair("email", "sentertainment@smail.com");
		BasicNameValuePair content = new BasicNameValuePair("content", form_input_comment.getText().toString()+" .");
		List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
		nameValuePairList.add(email);
		nameValuePairList.add(name_submit);
		nameValuePairList.add(content);
		UrlEncodedFormEntity encodedFormEntity;
		try {
			encodedFormEntity = new UrlEncodedFormEntity(nameValuePairList,"UTF-8");
			post.setEntity(encodedFormEntity);
			HttpResponse httpResponse = defaultHttpClient.execute(post);
			InputStream inputStream = httpResponse.getEntity().getContent();
			
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			stringBuilder = new StringBuilder();
			String bufferedStrChunk = null;

			while((bufferedStrChunk = bufferedReader.readLine()) != null){
				stringBuilder.append(bufferedStrChunk);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}
	public class submitComment extends AsyncTask<Void, Void, Void>{
		
		@Override
		protected Void doInBackground(Void... params) {
			SharedPreferences mPreferences =PreferenceManager.getDefaultSharedPreferences(DetailPostActivity.this);
			String name_comment = mPreferences.getString(ACCOUNT_NAME_DISPLAY, "Ẩn danh");
			if(id_activity==POST_ACTIVITY){
				sendPostRequestComment(URL_SUBMIT_COMMENT, name_comment);
			}else if (id_activity == PICTURE_ACTIVITY) {
				sendPostRequestComment(URL_SUBMIT_COMMENT_PICTURE, name_comment);
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			dialog.dismiss();
			CustomDialog info = new CustomDialog(getDialogContext());
			info.setDialogType(DIALOG_CONFIRM, getString(R.string.info_submit_comment_success));
			info.show();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(getDialogContext());
			dialog.setMessage("Đang gửi...");
			dialog.setCancelable(false);
			dialog.show();
		}
	}

}
